﻿namespace Digitalmes.Common.Utils;

/// <summary>
/// 条码规则校验器。
/// </summary>
public static class BarcodeChecker
{
    /// <summary>
    /// 校验多个条码规则。
    /// </summary>
    /// <param name="barcode">条码</param>
    /// <param name="rules">匹配规则集合</param>
    /// <param name="placeholder">规则中的占位字符</param>
    /// <param name="isWholeMatched">是否完整匹配。非完整匹配时条码长度不能短于规则长度，完整匹配时两者长度需完全相等。</param>
    /// <returns></returns>
    public static bool CheckMany(string barcode, IEnumerable<string> rules, char placeholder, bool isWholeMatched)
    {
        return rules.Any(rule => Check(barcode, rule, placeholder, isWholeMatched));
    }

    /// <summary>
    /// 校验条码规则。
    /// </summary>
    /// <param name="barcode">条码</param>
    /// <param name="rule">匹配规则</param>
    /// <param name="placeholder">规则中的占位字符</param>
    /// <param name="isWholeMatched">是否完整匹配。非完整匹配时条码长度不能短于规则长度，完整匹配时两者长度需完全相等。</param>
    /// <returns></returns>
    public static bool Check(string barcode, string rule, char placeholder, bool isWholeMatched)
    {
        // 条码长度不能小于规则长度；若完整匹配时，条码长度需等于规则长度
        if (barcode.Length < rule.Length || (isWholeMatched && barcode.Length != rule.Length))
        {
            return false;
        }

        for (int i = 0; i < rule.Length; i++)
        {
            if (rule[i] != barcode[i] && rule[i] != placeholder)
            {
                return false;
            }
        }

        return true;
    }
}
